package com.wnxy.sk.common.jwt;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

/**
 * 通过Hutool工具类生成token
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class JwtTemplate {

    private String path = "jwt.jks";
    private String keyStoreSecurity = "123456";
    private String alias = "jwt";

    /**
     * 创建密钥对对象
     */
    private KeyPair keyPair() {
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(
                new ClassPathResource(path),keyStoreSecurity.toCharArray()
        );
        KeyPair keyPair = factory.getKeyPair(alias);
        return keyPair;
    }

    /**
     * 创建签名器
     */
    private JWTSigner jwtSigner() {
        JWTSigner jwtSigner = JWTSignerUtil.createSigner("RSA",keyPair());
        return jwtSigner;
    }

    /**
     * 生成token
     */
    public String createToken(Map<String,Object> playload) {
        String token = JWTUtil.createToken(playload, jwtSigner());
        return token;
    }

    /**
     * 校验token
     */
    public boolean verify(String token){
        return JWTUtil.verify(token, jwtSigner());
    }

    /**
     * 解析token
     */
    public Object parseToken(String token,String key) {
        JWT jwt = JWTUtil.parseToken(token);
        return jwt.getPayload(key);
    }
}
